package com.bjpowernode.workbench.web.controller;

import com.bjpowernode.commons.contants.Contants;
import com.bjpowernode.commons.domain.ReturnObject;
import com.bjpowernode.commons.utils.DateUtils;
import com.bjpowernode.commons.utils.HSSFCellUtils;
import com.bjpowernode.settings.web.domain.User;
import com.bjpowernode.workbench.web.domain.Activity;
import com.bjpowernode.workbench.web.domain.ActivityRemark;
import com.bjpowernode.workbench.web.service.ActivityRemarkService;
import com.bjpowernode.workbench.web.service.ActivityService;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.lang.UsesJava7;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.java2d.pipe.AAShapePipe;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
public class WorkBenchIndexController {
    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityRemarkService activityRemarkService;

    @RequestMapping(value = "/workbench/index.do")
    public String index(){
        return "workbench/index";
    }

    @RequestMapping(value = "/workbench/main/index.do")
    public String mainIndex(){
        return "workbench/main/index";
    }

    @RequestMapping(value = "/workbench/activity/index.do")
    public String activityIndex(){
        return "workbench/activity/index";
    }

    @RequestMapping(value = "/workbench/activity/activityDetail.do")
    public String activityDetail(String id, HttpServletRequest request){
        try{
            Activity activity = activityService.selectActivityDetailById(id);
            List<ActivityRemark> activityRemarkList = activityRemarkService.selectActivityRemarkForDetailByActivityId(id);
//        将数据保存进request作用域中
            request.setAttribute("activity",activity);
            request.setAttribute("activityRemarkList",activityRemarkList);

        }catch (Exception e){
            e.printStackTrace();
        }
        return "workbench/activity/detail";
    }


    @ResponseBody
    @RequestMapping("/workbench/activity/saveCreateActivity.do")
    public Object saveCreateActivity(Activity activity, HttpSession session){
          User user = (User)session.getAttribute(Contants.SESSION_USER);

           activity.setId(UUID.randomUUID().toString().replaceAll("-",""));
           activity.setCreatetime(DateUtils.formateDateTime(new Date()));
           activity.setCreateby(user.getId());

        ReturnObject returnObject = new ReturnObject();
       try {
           int count = activityService.insertActivity(activity);
           if (count<=0){
               returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
               returnObject.setMessage("添加失败!!!");
               return returnObject;
           }else {
               returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
               returnObject.setMessage("添加成功");
               return returnObject;
           }
       }catch (Exception e){
          e.printStackTrace();
           returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
           returnObject.setMessage("添加失败!!!");
           return returnObject;
       }
    }


    @ResponseBody
    @RequestMapping("/workbench/activity/selectActivity.do")
    public Object selectActivity(Activity activity){
        Map<String,Object> map = new HashMap<>();
        int beginNo = (activity.getBeginNo()-1)*activity.getPageSize();
        activity.setBeginNo(beginNo);
        List<Activity> activityList = activityService.selectActivity(activity);
        int total = activityService.selectCountActivityByCondition(activity);
        map.put("activityList",activityList);
        map.put("total",total);
        return map;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/selectActivityCountByCondition.do")
    public int selectActivityCountByCondition(Activity activity){
        return activityService.selectCountActivityByCondition(activity);
    }



    @ResponseBody
    @RequestMapping("/workbench/activity/deleteActivityByIds.do")
    public Object deleteActivityByIds(String[] id){
       for(int i =0;i<id.length;i++){
           System.out.println(id[i]);
       }
         ReturnObject returnObject = new ReturnObject();
       try{
           int deleteTotals = activityService.deleteActivityByIds(id);
           if (deleteTotals>0){
               returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
               returnObject.setMessage("删除成功!");
           }else {
               returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
               returnObject.setMessage("删除失败!!!");
           }
       }catch (Exception e){
           e.printStackTrace();
           returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
           returnObject.setMessage("删除失败！！！");
       }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/updateActivityByIds.do")
    public Object updateActivityByIds(Activity activity,HttpSession session){
        User user = (User)session.getAttribute(Contants.SESSION_USER);
        activity.setEdittime(DateUtils.formateDateTime(new Date()));
        activity.setEditby(user.getId());
        ReturnObject returnObject = new ReturnObject();
       try{
           int updateTotal = activityService.updateActivityById(activity);

           if (updateTotal >0){
               returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
               returnObject.setMessage("成功修改！");
           }else {
               returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
               returnObject.setMessage("修改失败");
           }
       }catch (Exception e){
           e.printStackTrace();
       }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/selectActivityById.do")
    public Object selectActivityById(String id){

        Map<String,Object> map = new HashMap<>();
            Activity activity = activityService.selectActivityById(id);

            ReturnObject returnObject = new ReturnObject();
            map.put("activity",activity);
            map.put("returnObject",returnObject);
            if (activity==null){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("查询失败");
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("查询成功");
            }
        return map;
    }

    @RequestMapping("/workbench/activity/exportAllActivity.do")
    public void exportAllActivity(HttpServletResponse response) throws Exception{
        List<Activity> activityList = activityService.selectAllActivity();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("活动市场列表");
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("活动名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

       if(activityList!=null && activityList.size()>0){
           Activity activity = new Activity();
           for (int i=0;i<activityList.size();i++){
               activity = activityList.get(i);
               row = sheet.createRow(i+1);
               cell = row.createCell(0);
               cell.setCellValue(activity.getId());
               cell = row.createCell(1);
               cell.setCellValue(activity.getOwner());
               cell = row.createCell(2);
               cell.setCellValue(activity.getName());
               cell = row.createCell(3);
               cell.setCellValue(activity.getStartdate());
               cell = row.createCell(4);
               cell.setCellValue(activity.getEnddate());
               cell = row.createCell(5);
               cell.setCellValue(activity.getCost());
               cell = row.createCell(6);
               cell.setCellValue(activity.getDescription());
               cell = row.createCell(7);
               cell.setCellValue(activity.getCreatetime());
               cell = row.createCell(8);
               cell.setCellValue(activity.getCreateby());
               cell = row.createCell(9);
               cell.setCellValue(activity.getEdittime());
               cell = row.createCell(10);
               cell.setCellValue(activity.getEditby());
           }
       }
//       根据workbook对象生成excel文件
//        long startTime = System.currentTimeMillis();
//        OutputStream os = new FileOutputStream("D:\\动力节点crm项目学习（ssm框架）\\excelDownload\\activityList.xls");
//       workbook.write(os);
//       os.close();
//       workbook.close();

//       把生成的excel文件下载到客户端
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
        OutputStream out = response.getOutputStream();
//        InputStream is = new FileInputStream("D:\\动力节点crm项目学习（ssm框架）\\excelDownload\\activityList.xls");
//        byte[] buff = new byte[256];
//        int len =0;
//        while ((len=is.read(buff))!=-1){
//            out.write(buff,0,len);
//        }
//        long endTime = System.currentTimeMillis();
//        is.close();

//        直接采用workbook提供的输出方法批量导出的效率更高！！！
        workbook.write(out);
        workbook.close();
        out.flush();
//        System.out.println("----------------"+(endTime-startTime));
    }

    @RequestMapping("/workbench/activity/exportCheckedActivity.do")
    public void exportCheckedActivity(String[] id,HttpServletResponse response) throws Exception {
        System.out.println(id.length+"-----------------------");
        List<Activity> activityList = activityService.selectCheckedActivity(id);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("活动列表");
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("活动名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

        if (activityList.size() > 0 && activityList != null) {
            Activity activity = new Activity();
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell = row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(2);
                cell.setCellValue(activity.getName());
                cell = row.createCell(3);
                cell.setCellValue(activity.getStartdate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getEnddate());
                cell = row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreatetime());
                cell = row.createCell(8);
                cell.setCellValue(activity.getCreateby());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEdittime());
                cell = row.createCell(10);
                cell.setCellValue(activity.getEditby());
            }
        }


        OutputStream out = response.getOutputStream();
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=activityList.xls");
        workbook.write(out);
        workbook.close();
        out.flush();
    }


    @ResponseBody
    @RequestMapping("/workbench/activity/fileUpload.do")
    public Object fileUpload(MultipartFile myFile,String name) throws Exception{

        //        获取文件全名（包括后缀名）
        String fileName = myFile.getOriginalFilename();
        File file = new File("D:\\动力节点crm项目学习（ssm框架）\\excelFileUpload"+fileName);
        myFile.transferTo(file);

        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
        returnObject.setMessage("上传成功");
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/insertActivityByList.do")
    public Object insertActivityByList(MultipartFile activityFile,HttpSession session) {
        User user = (User) session.getAttribute(Contants.SESSION_USER);
        List<Activity> activityList = new ArrayList<>();
        ReturnObject returnObject = new ReturnObject();
//        获取文件全名（包括后缀名）
        try {
//            把excel写到磁盘里面
//            String fileName = activityFile.getOriginalFilename();
//            File file = new File("D:\\动力节点crm项目学习（ssm框架）\\excelFileUpload\\", fileName);
//            activityFile.transferTo(file);

            //       从磁盘中获取excel文件内容输入到wb里面
//            InputStream is = new FileInputStream("D:\\动力节点crm项目学习（ssm框架）\\excelFileUpload\\" + fileName);

//            直接从内从中获取数据写到wb里面（效率更高，省略了写到磁盘在从磁盘写到wb里面的过程，读磁盘效率非常低）
            InputStream is = activityFile.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(is);
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = null;
            HSSFCell cell = null;

            for (int i = 0; i < sheet.getLastRowNum(); i++) {
                Activity activity = new Activity();
                activity.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                activity.setOwner(user.getId());
                activity.setCreateby(user.getId());
                activity.setCreatetime(DateUtils.formateDateTime(new Date()));
                row = sheet.getRow(i + 1);
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    cell = row.getCell(j);
//                    因为列值的获取要根据内容的类型对应获取，所以调用自己封装的方法获取列值。
                    String cellValue = HSSFCellUtils.getHSSFCellValueForStr(cell);
                    if (j == 0) {
                        activity.setName(cellValue);
                    } else if (j == 1) {
                        activity.setStartdate(cellValue);
                    } else if (j == 2) {
                        activity.setEnddate(cellValue);
                    } else if (j == 3) {
                        activity.setCost(cellValue);
                    } else if (j == 4) {
                        activity.setDescription(cellValue);
                    }
                }
                activityList.add(activity);
            }
//            插入成功条数
            int ret = activityService.insertActivityByList(activityList);

            returnObject.setRetData(ret);
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);

        } catch (Exception e) {
           for (int i=0;i<activityList.size();i++){
               System.out.println(activityList.get(i).getId());
               System.out.println(activityList.get(i).getName());
           }
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("导入失败");
            e.printStackTrace();
        }
        return returnObject;
    }


    @ResponseBody
    @RequestMapping("/workbench/activity/insertActivityRemark.do")
    public Object insertActivityRemark(ActivityRemark activityRemark,HttpSession session) {
        ReturnObject returnObject = new ReturnObject();
        User user = (User) session.getAttribute(Contants.SESSION_USER);
        activityRemark.setId(UUID.randomUUID().toString().replaceAll("-",""));
        activityRemark.setCreateTime(DateUtils.formateDateTime(new Date()));
        activityRemark.setEditFlag(Contants.REMARK_EDIT_FLAG_NO_EDIT);
        activityRemark.setCreateBy(user.getId());
        int insertCount = activityRemarkService.insertActivityRemark(activityRemark);

        if (insertCount>0){
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setRetData(activityRemark);
            returnObject.setMessage("发表备注成功");
        }else {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
        }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/deleteActivityRemarkById.do")
    public Object deleteActivityRemarkById(String id) throws Exception {
        int delCount = activityRemarkService.deleteActivityRemarkById(id);
        if (id==null ||id ==""){
           throw new Exception("id为空或者为null");
        }
        ReturnObject returnObject = new ReturnObject();
        if (delCount>=0){
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
        }else {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
        }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/updateActivityRemark.do")
    public Object updateActivityRemark(ActivityRemark activityRemark ,HttpSession session){
        ReturnObject returnObject = new ReturnObject();
        User user  = (User) session.getAttribute(Contants.SESSION_USER);
        try {
            activityRemark.setEditFlag(Contants.REMARK_EDIT_FLAG_YES_EDIT);
            activityRemark.setEditTime(DateUtils.formateDateTime(new Date()));
            activityRemark.setEditBy(user.getId());
            int updateCount = activityRemarkService.updateActivityRemarkById(activityRemark);
            if(updateCount<=0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(activityRemark);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/selectActivityRemark.do")
    public Object selectActivityRemark(String id){
        ReturnObject returnObject = new ReturnObject();
        ActivityRemark activityRemark = activityRemarkService.selectActivityRemarkById(id);
        if(activityRemark!=null){
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setRetData(activityRemark);
        }else {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
        }
        return returnObject;
    }

    }

